<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试支付</title>
</head>
<body>
    <h1>测试支付页面</h1>
    
    <form id="paymentForm">
        <label for="orderId">订单ID:</label>
        <input type="text" id="orderId" name="orderId" required><br><br>

        <label for="orderTotalAmount">订单金额:</label>
        <input type="number" step="0.01" id="orderTotalAmount" name="orderTotalAmount" required><br><br>

        <label for="jwtToken">JWT Token:</label>
        <input type="text" id="jwtToken" name="jwtToken" required><br><br>

        <button type="button" onclick="submitOrder()">提交支付</button>
    </form>

    <div id="result"></div>

    <script>
        async function submitOrder() {
            const orderId = document.getElementById('orderId').value;
            const orderTotalAmount = document.getElementById('orderTotalAmount').value;
            const jwtToken = document.getElementById('jwtToken').value;

            if (!orderId || !orderTotalAmount || !jwtToken) {
                alert("请填写完整的订单信息和JWT Token！");
                return;
            }

            const paymentRequest = {
                orderId: orderId,
                orderTotalAmount: parseFloat(orderTotalAmount).toFixed(2)
            };

            try {
                const response = await fetch('http://localhost:8080/pay', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${jwtToken}`
                    },
                    body: JSON.stringify(paymentRequest)
                });

                if (response.ok) {
                    const result = await response.text();
                    // 动态插入支付宝支付表单并自动提交
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(result, 'text/html');
                    const form = doc.querySelector('form');

                    if (form) {
                        document.body.innerHTML = ''; // 清空当前页面内容
                        document.body.appendChild(form); // 插入支付宝表单
                        form.submit(); // 自动提交表单
                    } else {
                        document.getElementById('result').innerHTML = '支付页面加载失败，请重试！';
                    }
                } else {
                    const errorText = await response.text();
                    document.getElementById('result').innerHTML = `支付请求失败: ${errorText}`;
                }
            } catch (error) {
                console.error('支付请求出错:', error);
                document.getElementById('result').innerHTML = '支付请求出错，请稍后再试！';
            }
        }
    </script>
</body>
</html>
